package net.koodar.forge.common.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * 程序启动后执行
 *
 * @author liyc
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class StartedListener implements ApplicationListener<ApplicationStartedEvent> {

    @Value("${forge.common.doc.enabled}")
    private String documentationEnabled;

    private final WebServerApplicationContext webServerApplicationContext;

    public StartedListener(WebServerApplicationContext webServerApplicationContext) {
        this.webServerApplicationContext = webServerApplicationContext;
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        this.printStartInfo();
    }

    private void printStartInfo() {
        String appUrl = "127.0.0.1:" + webServerApplicationContext.getWebServer().getPort();
        log.info(AnsiOutput.toString(AnsiColor.BRIGHT_BLUE, "Forge Admin started at         ", appUrl));
        if (documentationEnabled != null && documentationEnabled.equals("true")) {
            log.debug(AnsiOutput
                    .toString(AnsiColor.BRIGHT_BLUE, "Forge api documentation was enabled at  ", appUrl,
                            "/swagger-ui.html"));
        }
        log.info(AnsiOutput.toString(AnsiColor.BRIGHT_YELLOW, "Forge has started successfully!"));
    }
}
